<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form action="xxx.com" method="POST" id="form">
    请输入用户名: <input type="text" name="username">
    请输入密码: <input type="password" name="password">
    请输入手机号: <input type="text" name="phone">
    <button>提交</button>
  </form>
  <script>
    // var form = document.getElementById('form')
    // form.onsubmit = function () {
    //   if (form.username.value === '') {
    //     alert('用户名不能为空')
    //     return false
    //   }
    //   if (form.password.value.length < 6) {
    //     alert('密码长度不能小于6')
    //     return false
    //   }
    //   if (!/^1[3|5|7|8|][0-9]{9}$/.test(form.phone.value)) {
    //     alert('手机号格式不对')
    //     return false
    //   }
    // }

    var form = document.getElementById('form')
    var check = {
      isNonEmpty: function (value, errorMsg) {
        if (value === '') {
          return errorMsg
        }
      },
      minLength: function (value, length, errorMsg) {
        if (value.length < 6) {
          return errorMsg
        }
      },
      isMobile: function (value, errorMsg) {
        if (!/^1[3|5|7|8][0-9]{9}$/.test(value)) {
          return errorMsg
        }
      }
    }

    var validateFun = function () {
      var validator = new Validator()
      validator.add(form.username, 'isNonEmpty', '用户名不能为空')
      validator.add(form.password, 'minLength:6', '密码长度不能小于6')
      validator.add(form.phone, 'isMobile', '手机号格式不对')
      var errorMsg = validator.start()
      return errorMsg
    }

    form.onsubmit = function () {
      var errorMsg = validateFun()
      // console.log(errorMsg)
      if (errorMsg) {
        alert(errorMsg)
        return false
      }
    }

    // 封装策略类 构造函数 class
    var Validator = function () {
      // 保存验证规则的数组
      this.chche = []
    }

    Validator.prototype.add = function (dom, rule, errorMsg) {
      console.log(dom, rule, errorMsg)
      var ary = rule.split(':') // split() 方法用于把一个字符串分割成字符串数组。
      console.log('ary', ary)
      this.chche.push(function () {
        var strategy = ary.shift() // 用户选择的验证规则 shift() 用于把数组的第一个元素从其中删除，并返回第一个元素的值。
        console.log('ary.shift()', strategy)
        ary.unshift(dom.value) // unshift() 方法可向数组的开头添加一个或更多元素，并返回新的长度。
        console.log('ary.unshift()', dom.value)
        ary.push(errorMsg)
        console.log('ary.push()', errorMsg)
        // return check[strategy].apply(dom, ary)
        return check[strategy](...ary)
      })
    }

    Validator.prototype.start = function () {
      console.log('chche', this.chche)
      for (var i = 0, vaFunc; vaFunc = this.chche[i++];) {
        // console.log('vaFunc', vaFunc)
        var msg = vaFunc()
        if (msg) {
          return msg
        }
      }
    }
  </script>
</body>
</html>